<template>
  <div class="kgh-container show">
    <div class="layout" v-show="qrShow" @click.stop="qrShow=false">
      <div class="layout-content qrcode">
        <template v-if="qrType==1">
          <p>扫码分享到微信：</p>
          <canvas id="canvas"></canvas>
        </template>
        <template v-if="qrType==2">
          <p>打开微信扫一扫支付</p>
          <canvas id="canvas"></canvas>
          <div class="btn-box">
            <button class="btn btn-success" @click.stop="handlePayCheck()" style="margin-right:20px;">支付成功</button>
            <button class="btn btn-danger" @click.stop="handlePayError()">支付遇到问题</button>
          </div>
        </template>
      </div>
    </div>
    <div class="section sec-mrb">
      <div class="container">
        <div class="row">
          <div class="video-show clearfix">
            <div class="video-bg"></div>
            <div class="col-md-9 col-xs-12">
              <div class="video-box" ref="video">
                <div id="playercontainer">
                  <video-player v-if="unitDetail" class="video-player-box" ref="videoPlayer" :options="playerOptions" :playsinline="true" customEventName="customstatechangedeventname" @play="onPlayerPlay($event)" @pause="onPlayerPause($event)">
                  </video-player>
                </div>
              </div>
            </div>
            <div class="col-md-3 col-xs-12">
              <div class="video-info">
                <!-- <div class="video-top text-center">
                课程作者
              </div> -->
                <div class="video-center text-center">
                  <template v-if="unitDetail">
                    <a href="javascript:;">
                      <img :src="'https://kegonghui.oss-cn-beijing.aliyuncs.com/'+unitDetail.author.headimg+'?x-oss-process=image/circle,r_100'" class="img-circle" width="116" height="116" />
                    </a>
                    <h4 class="author-name">{{unitDetail.author.nickname}}</h4>
                    <p class="author-info color-hint">
                      <span>{{unitDetail.author.workYear}}年</span>
                      <span>{{unitDetail.author.title}}</span>
                    </p>
                    <p class="text-primary unti-price">¥ {{unitDetail.curriculum?unitDetail.curriculum.price:0}}</p>
                    <div class="unit-buy" v-if="!unitDetail.auth||paySuccess">
                      <button class="btn btn-success" @click="handleBuy()">立即购买</button>
                    </div>
                    <p class="unit-day color-hint">上传日期：{{timestampToTime(unitDetail.curriculum.createTime)}}</p>
                    <div class="video-handle">
                      <button v-if="!unitDetail.isCollection" class="btn btn-ghost" style="margin-right:10px" @click="handleAddCollection()">关注</button>
                      <button class="btn btn-ghost" @click="handleQrcode(1,window.location.href)">分享</button>
                    </div>
                  </template>
                </div>
                <!-- <a href="javascript:;" class="video-bottom text-center" @click="handleQrcode(window.location.href)">
                分享到微信
              </a> -->
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-xs-12 video-desc">
            <div class="clearfix video-desc-details">
              <div class="col-sm-8 col-xs-12">
                <p class="video-title" v-if="unitDetail&&unitDetail.curriculum">{{unitDetail.curriculum.curriculumName}}--{{unitDetail.name}}(已更新到第{{unitList.length}}章)</p>
              </div>
              <div class="col-sm-4 col-xs-12">
                <a :href="'https://kegonghui.oss-cn-beijing.aliyuncs.com/'+unitDetail.accessoriesUrl" target="_blank" v-if="unitDetail" class="text-primary">附件：{{unitDetail.accessoriesName}}</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="section sec-mrb">
      <div class="container">
        <div class="row section-header">
          <div class="col-xs-12">
            <h3>章节共{{unitList.length}}章
              <a href="javascript:;" class="pull-right" @click="handleToMore(4)">
                <small>更多</small>
              </a>
            </h3>
          </div>
        </div>
        <div class="unit-list">
          <template v-for="(item,index) in unitList">
            <div class="row unit-item" :key="item.id" v-if="index<5">
              <div class="col-xs-9">
                <router-link :to="'/show/'+item.curriculumId+'/'+item.id">
                  章节{{index+1}}.&nbsp;&nbsp;{{item.name}}
                  <button class="btn-blue" v-if="(unitDetail&&unitDetail.curriculum&&unitDetail.curriculum.price==0)||paySuccess">免费</button>
                </router-link>
              </div>
              <div class="col-xs-3 text-right">

              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="section sec-mrb">
      <div class="container">
        <div class="row section-header">
          <div class="col-xs-12">
            <h3>相关课程</h3>
          </div>
        </div>
        <div class="row">
          <div class="col-xs-12 col-sm-3" v-for="item in cumList" :key="item.id">
            <Course-item :item="item"></Course-item>
          </div>
        </div>
      </div>
    </div>
    <div class="section">
      <div class="container">
        <div class="row section-header">
          <div class="col-xs-12">
            <h3>留言板</h3>
          </div>
        </div>
        <div class="row" style="margin-bottom: 20px;">
          <div class="col-xs-12">
            <textarea v-model="addMes" class="form-control" rows="3"></textarea>
          </div>
        </div>
        <div class="row text-right">
          <div class="col-xs-12">
            <button class="btn-blue" @click="handleAddMessage()">留言</button>
          </div>
        </div>
        <div class="row txt-list" style="margin-bottom: 10px;">
          <div class="col-xs-12">
            <div class="txt-item" v-for="item in leaveWordList" :key="item.id">
              <p>
                <a href="javascript:;" class="txt-user text-primary"><img :src="'https://kegonghui.oss-cn-beijing.aliyuncs.com/'+item.fromHeadimg+'?x-oss-process=image/circle,r_100'" width="30" class="img-circle">{{item.fromName}}:</a>{{item.content}}</p>
            </div>
          </div>
        </div>
        <div class="row text-center load-more" v-if="loadShow">
          <a href="javascript:;" @click="fetchMoreData()">加载更多</a>
        </div>
      </div>
    </div>

  </div>
</template>


<script>
import axios from 'axios'
import qs from 'qs'
import util from '@/assets/js/utils.js'
import 'video.js/dist/video-js.css'
import { videoPlayer } from 'vue-video-player'
import QRCode from 'qrcode'
import wx from 'weixin-js-sdk'

export default {
  name: 'video-show',
  data () {
    return {
      cid: '',
      uid: '',
      openid: '',
      leaveWordList: [],
      cumList: [],
      unitList: [],
      unitDetail: null,
      addMes: '',
      buyFrom: 'web', //支付来源
      qrShow: false,
      qrType: 1, //1 分享 2 微信支付
      checkTimer: null,
      order: null, //订单信息
      paySuccess: false, //支付成功
      loadShow: true,
      pageNum: -1
    }
  },
  components: {
    videoPlayer
  },
  created () {
    this.handleInitPage();
  },
  mounted () { },
  watch: {
    $route () {
      this.handleInitPage();
    }
  },
  computed: {
    player () {
      return this.$refs.videoPlayer.player
    },
    userInfo () {
      return this.$store.state.userInfo
    },
    videoWidth () {
      return this.$refs['video'].offsetWidth
    },
    playerOptions () {
      return {
        // videojs options
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: 'video/mp4',
            src: this.unitDetail.videoUrl //你的视频地址（必填）
          }
        ],
        poster: this.unitDetail.curriculum.cimgUrl, //你的封面地址
        width: document.documentElement.clientWidth,
        notSupportedMessage: '此视频暂无法播放，请稍后再试' //允许覆盖Video.js无法播放媒体源时显示的默认信息。
      }
    }
  },
  methods: {
    handleInitPage () {
      let cid = this.$route.params.cid
      let uid = this.$route.params.uid ? this.$route.params.uid : ''
      this.cid = cid
      this.uid = uid
      this.fetchDetails()
      this.fetchCoumList()
      this.fetchUnitList()
      this.fetchMoreData()
      if (this.isWeiXin()) {
        if (this.getQueryString('state') == 'wechat') {
          let code = this.getQueryString('code')
          this.fetchUserOpenid(code)
        } else {
          let href = 'http://www.kegonghui.com/#/show/' + cid
          if (uid) href += '/' + uid
          window.location.href =
            'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx578871d82499b741&redirect_uri=' +
            encodeURIComponent(href) +
            '&response_type=code&scope=snsapi_base&state=wechat#wechat_redirect'
          this.buyFrom = 'wechat'
        }
      }
    },
    // listen event
    onPlayerPlay (player) {
      // console.log('player play!', player)
    },
    onPlayerPause (player) {
      // console.log('player pause!', player)
    },
    // ...player event

    // or listen state event
    playerStateChanged (playerCurrentState) {
      // console.log('player current update state', playerCurrentState)
    },

    // player is ready
    playerReadied (player) {
      console.log('the player is readied', player)
      // you can use it to do something...
      // player.[methods]
    },
    handleAddMessage () {
      //新增留言
      let that = this
      let params = qs.stringify({
        cid: that.cid,
        content: that.addMes,
        rid: 1
      })
      axios
        .post('/curriculum/addLeaveWord', params)
        .then(function (response) {
          if (response.data.suc == 200) {
            that.leaveWordList.unshift(response.data.data)
            that.addMes = ''
          } else if (response.data.errCode == 'ERROR_CODE_000000') {
            util.loginOver.call(that)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    fetchMessageList () {
      //留言列表
      let that = this
      let params = qs.stringify({
        cid: that.cid,
        from: that.pageNum
      })
      axios
        .post('/curriculum/leaveWordList', params)
        .then(function (response) {
          if (response.data.suc == 200) {
            if (response.data.data.length <= 0) that.loadShow = false
            that.leaveWordList = that.leaveWordList.concat(response.data.data)
          } else if (response.data.errCode == 'ERROR_CODE_000000') {
            util.loginOver.call(that)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },

    fetchCoumList () {
      // 获取课程列表
      let that = this
      let params = qs.stringify({
        ctype: 1,
        category: 1,
        hot: 1,
        name: '',
        from: ''
      })
      axios
        .post('/curriculum/list', params)
        .then(function (response) {
          if (response.data.suc == 200) {
            that.cumList = response.data.data
          } else if (response.data.errCode == 'ERROR_CODE_000000') {
            util.loginOver.call(that)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },

    fetchUnitList () {
      // 获取单元列表
      let that = this
      let params = qs.stringify({
        id: this.cid
      })
      axios
        .post('/curriculum/unitList', params)
        .then(function (response) {
          if (response.data.suc == 200) {
            that.unitList = response.data.data
          } else if (response.data.errCode == 'ERROR_CODE_000000') {
            util.loginOver.call(that)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },

    fetchDetails (val) {
      // 观看某一单元(单元详情)
      let that = this
      let params = {
        curriculumId: that.cid,
        id: that.uid
      }
      if (this.uid) params['unitId'] = this.uid
      axios
        .post('/curriculum/getUnit', qs.stringify(params))
        .then(function (response) {
          if (response.data.suc == 200) {
            if (response.data.data.isLogin) {
              that.unitDetail = response.data.data
            } else {
              util.loginOver.call(that)
            }
          } else if (response.data.errCode == 'ERROR_CODE_000000') {
            util.loginOver.call(that)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    handleBuy () {
      // 购买课程，支付
      if (this.unitDetail.auth) {
        alert('不能购买自己的课程')
        return false
      }
      let params = {
        curriculumId: this.cid,
        from: this.buyFrom
      }
      if (this.uid) params['id'] = this.uid
      let that = this
      axios
        .post('/pay/buyCurr', qs.stringify(params))
        .then(function (response) {
          if (response.data.suc == 200) {
            that.order = response.data.data
            if (that.buyFrom == 'web') {
              that.handleQrcode(2, response.data.data.code_url)
            } else {
              that.handleWxPay()
            }
          } else if (response.data.errCode == 'ERROR_CODE_000000') {
            util.loginOver.call(that)
          } else if (response.data.errCode == 'ERROR_CODE_200004') {
            alert('已经购买！')
          } else {
            alert('购买失败！')
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    handlePayCheck () {
      let that = this
      let params = {
        orderId: that.order.orderId
      }
      axios
        .post('/pay/check', qs.stringify(params))
        .then(function (response) {
          if (response.data.suc == 200) {
            that.paySuccess = true
            location.reload();
            alert('支付成功!')
          } else {
            alert('支付失败!')
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    handlePayError () {
      alert('支付出现问题，请拨打客服电话xxxx')
    },
    handleQrcode (type, href) {
      //分享，动态生成二维码，可以添加变量
      this.qrType = type
      this.qrShow = true
      let queryDetail = href
      var canvas = document.getElementById('canvas')
      QRCode.toCanvas(canvas, queryDetail, function (error) {
        if (error) console.error(error)
        console.log('success!')
      })
    },
    timestampToTime (time) {
      return util.timestampToTime(time)
    },
    handleAddCollection () {
      // 添加关注
      let that = this
      axios
        .post(
          '/curriculum/addCollection',
          qs.stringify({
            id: this.cid,
            type: 1
          })
        )
        .then(function (response) {
          if (response.data.suc == 200) {
            alert('关注成功')
          } else if (response.data.errCode == 'ERROR_CODE_000000') {
            util.loginOver.call(that)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    isWeiXin () {
      //window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
      var ua = window.navigator.userAgent.toLowerCase()
      //通过正则表达式匹配ua中是否含有MicroMessenger字符串
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true
      } else {
        return false
      }
    },
    getQueryString (name) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
      var r = window.location.search.substr(1).match(reg)
      if (r != null) {
        return unescape(r[2])
      }
      return null
    },
    fetchUserOpenid (code) {
      let that = this
      axios
        .post(
          '/user/openid',
          qs.stringify({
            code: code
          })
        )
        .then(function (response) {
          if (response.data.suc == 200) {
            that.openid = response.data.data.openid
          } else if (response.data.errCode == 'ERROR_CODE_000000') {
            util.loginOver.call(that)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    handleWxPay () {
      if (typeof wx.WeixinJSBridge == 'undefined') {
        if (document.addEventListener) {
          document.addEventListener(
            'WeixinJSBridgeReady',
            this.onBridgeReady,
            false
          )
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady)
          document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady)
        }
      } else {
        this.onBridgeReady()
      }
    },
    onBridgeReady () {
      let that = this
      let order = this.order
      wx.WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          appId: order.appId, //公众号名称，由商户传入
          timeStamp: order.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: order.nonceStr, //随机串
          package: 'prepay_id=' + order.package,
          signType: 'MD5', //微信签名方式：
          paySign: order.paySign //微信签名
        },
        function (res) {
          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            that.handlePayCheck()
            // 使用以上方式判断前端返回,微信团队郑重提示：
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          } else {
            that.handlePayCheck()
          }
        }
      )
    },
    fetchMoreData () {
      // 加载更多
      this.pageNum += 1
      this.fetchMessageList()
    }
  }
}
</script>
<style lang="scss" scoped>
.txt-list {
  margin-top: 20px;
  .txt-item {
    padding: 10px 0px;
    border-bottom: 1px solid #e8e8e8;
    p {
      margin: 0;
      word-wrap: break-word;
      img,
      .txt-user {
        margin-right: 10px;
        white-space: nowrap;
      }
    }
  }
}
.unit-list {
  .unit-item {
    padding: 10px 0px;
    // border-bottom: 1px solid #b8b8b8;
    font-size: 16px;
    &:last-child {
      border: none;
    }
    .btn-blue {
      margin: 10px;
      padding: 2px 12px;
      font-size: 12px;
    }
  }
}
.video-show {
  position: relative;
  // background-color: #eeeeee;
  // background-position: 15px 15px;
  .video-bg {
    position: absolute;
    top: 0;
    left: 15px;
    right: 15px;
    bottom: 0;
    background-color: #eeeeee;
  }
  .video-info {
    padding: 30px;
    .video-center {
      padding-top: 20px;
      .author-name {
        padding: 10px 0px 5px;
      }
      .author-info {
        span {
          display: inline-block;
          width: 50%;
          text-align: center;
        }
      }
      .unti-price {
        font-size: 30px;
        padding: 5px 0px;
      }
      .unit-buy {
        margin-bottom: 10px;
        button {
          width: 100%;
        }
      }
      .unit-day {
        font-size: 12px;
      }
      .video-handle {
        margin-top: 30px;
      }
    }
  }
}
.video-desc {
  .video-desc-details {
    background: #b8b8b8;
    padding: 15px;
    color: #ffffff;
    line-height: 40px;
  }
  p {
    margin: 0;
    &.video-title {
      font-size: 20px;
    }
  }
}
// .video-show {
//   position: relative;
//   .video-box {
//     position: relative;
//     min-height: 500px;
//   }
//   .video-center {
//     padding: 25px 20px;
//     .img-circle {
//       margin-bottom: 20px;
//     }
//     .video-top,
//     .video-bottom {
//       display: block;
//       height: 50px;
//       line-height: 50px;
//       color: #ffffff;
//     }
//     .video-top {
//       background: #7ed321;
//     }
//     .video-bottom {
//       background: #f5a623;
//     }
//   }
//   .video-info {
//     background: #eeeeee;
//     .video-handle {
//       margin-top: 30px;
//     }
//   }
// }
</style>

